
local U = require "packages/hanqing/util"

local jieqian = fk.CreateSkill{
  name = "hanqing__jieqian",
  tags = { U.VerticalAlliance },
  attached_skill_name = "hanqing__jieqian&",
}

Fk:loadTranslationTable {
  ["hanqing__jieqian"] = "解箝",
  [":hanqing__jieqian"] = "<a href='hanqing__alliance_skill'>合纵技</a>，"..
  "出牌阶段限一次，你可以将一张装备牌置于其他角色的装备区（可替换原装备），"..
  "然后攻击范围内角色数因此变少的角色各回复1点体力。<br>"..
  "捭阖：一张装备牌被替换后，你可以令一名角色获得之，然后将其武将牌状态调整至与你相同。",

  ["#hanqing__jieqian"] = "解箝：将一张装备置入其他角色装备区（替换原装备），攻击范围内角色数因此变少的角色回复体力",
  ["#hanqing__jieqian-choose"] = "解箝：你可以令一名角色获得%arg，其武将牌状态调整至与你相同",
}

jieqian:addEffect("active", {
  anim_type = "support",
  prompt = "#hanqing__jieqian",
  card_num = 1,
  target_num = 1,
  can_use = function (self, player)
    return player:usedEffectTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, player, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeEquip
  end,
  target_filter = function(self, player, to_select, selected, selected_cards)
    return #selected == 0 and #selected_cards == 1 and to_select ~= player and
      to_select:canMoveCardIntoEquip(selected_cards[1], true)
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    local target = effect.tos[1]
    local nums = table.map(room.players, function (p)
      return #table.filter(room.alive_players, function (q)
        return p:inMyAttackRange(q)
      end)
    end)
    room:moveCardIntoEquip(target, effect.cards[1], jieqian.name, true, player)
    local nums2 = table.map(room.players, function (p)
      return #table.filter(room.alive_players, function (q)
        return p:inMyAttackRange(q)
      end)
    end)
    for _, p in ipairs(room:getAlivePlayers()) do
      if not p.dead and nums[table.indexOf(room.players, p)] > nums2[table.indexOf(room.players, p)] then
        room:recover{
          who = p,
          num = 1,
          recoverBy = player,
          skillName = jieqian.name,
        }
      end
    end
  end,
})

jieqian:addEffect(fk.AfterCardsMove, {
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(jieqian.name) then
      local ids = {}
      for _, move in ipairs(data) do
        if move.from and move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip and
              Fk:getCardById(info.cardId).type == Card.TypeEquip and
              table.contains(player.room.discard_pile, info.cardId) then
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
      end
      ids = player.room.logic:moveCardsHoldingAreaCheck(ids)
      if #ids > 0 then
        event:setCostData(self, {cards = ids})
        return true
      end
    end
  end,
  on_trigger = function (self, event, target, player, data)
    local cards = table.simpleClone(event:getCostData(self).cards) or {}
    for _, id in ipairs(cards) do
      if not player:hasSkill(jieqian.name) then return end
      if table.contains(player.room.discard_pile, id) then
        event:setCostData(self, {id = id})
        self:doCost(event, target, player, data)
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local id = event:getCostData(self).id or 1
    local to = room:askToChoosePlayers(player, {
      min_num = 1,
      max_num = 1,
      targets = room.alive_players,
      skill_name = jieqian.name,
      prompt = "#hanqing__jieqian-choose:::"..Fk:getCardById(id):toLogString(),
      cancelable = true,
    })
    if #to > 0 then
      event:setCostData(self, {tos = to, id = id})
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    local id = event:getCostData(self).id or 1
    room:moveCardTo(id, Card.PlayerHand, to, fk.ReasonJustMove, jieqian.name, nil, true, to)
    if to.dead then return end
    if player.chained and not to.chained then
      to:setChainState(true)
    elseif not player.chained and to.chained then
      to:setChainState(false)
    end
    if to.dead then return end
    if player.faceup and not to.faceup then
      to:turnOver()
    elseif not player.faceup and to.faceup then
      to:turnOver()
    end
    if to.dead then return end
    if U.getAlliance(player) ~= U.getAlliance(to) then
      U.setAlliance(to, U.getAlliance(player))
    end
  end,
})

jieqian:addAcquireEffect(function (self, player, is_start)
  player.room:handleAddLoseSkills(player, "hanqing__baihe&", nil, false)
end)

jieqian:addLoseEffect(function (self, player, is_death)
  if not table.find(player:getSkillNameList(), function (s)
    return Fk.skills[s]:hasTag(U.VerticalAlliance) or Fk.skills[s]:hasTag(U.HorizontalAlliance)
  end) then
    player.room:handleAddLoseSkills(player, "-hanqing__baihe&", nil, false)
  end
end)

return jieqian
